<?php

class Manga_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    /**
     * Model to get all manga available
     * @return type 
     */
    function getManga_all() {
        $query = $this->db->order_by("name", "asc")->get('manga');

        $arr = array();
        foreach ($query->result() as $row) {
            $arr[] = $row;
        }
        return $arr;
    }

    /**
     * Add new manga
     * @param type $arr array information of manga to add
     * @return type 
     */
    function addManga($arr) {
        $data = array(
            'name' => $arr['name'],
            'oname' => $arr['oname'],
            'slug' => slug($arr['name']),
            'author' => $arr['author'],
            'translator' => $arr['translator'],
            'description' => $arr['description'],
            'status' => $arr['status'],
            'cover' => $arr['cover'],
            'created' => REQUEST_TIME,
            'update' => 0
        );
        $result = $this->db->insert('manga', $data);
        return $result;
    }

    /**
     * Edit manga infor
     * @param type $arr array information of manga to edit
     * @return type 
     */
    function editManga($arr) {
        $data = array(
            'name' => $arr['name'],
            'oname' => $arr['oname'],
            'slug' => slug($arr['name']),
            'author' => $arr['author'],
            'translator' => $arr['translator'],
            'description' => $arr['description'],
            'status' => $arr['status'],
            'cover' => $arr['cover'],
            'update' => REQUEST_TIME
        );

        $this->db->where('id', $arr['id']);
        $result = $this->db->update('manga', $data);
        return $result;
    }

    /**
     * Remove a manga out of Database
     * @param type $id id of manga
     * @return type 
     */
    function removeManga($id) {
        return $this->db->delete('manga', array('id' => $id));
    }

    /**
     * Validate manga infor before add to DB 
     * @param type $arr array data of manga 
     * @return type 
     */
    function addManga_validate($arr) {
        extract($arr);

        $err = 0;
        $msg = array();
        // validate username
        if (!$this->validateName($name)) {
            $err = -1;
            $msg['name'] = 'Manga Name invalid';
        }

        //check manga other name exit
        if (!$this->validateName($oname)) {
            $err = -1;
            $msg['oname'] = 'Manga Other name invalid';
        }

        //check manga author name
        if (!$this->validateName($author)) {
            $err = -1;
            $msg['author'] = 'Author name invalid';
        }

        //check manga translator name
        if (!$this->validateName($translator)) {
            $err = -1;
            $msg['translator'] = 'ranslator name invalid';
        }

        // validate Description
        if (!$this->validateDescription($desc)) {
            $msg['desc'] = 'Description invalid';
            $err = -1;
        }
        //check manga name exit
        $id = isset($id) ? $id : 0;
        if ($this->checkNameExist($name, $id)) {
            $msg['name'] = 'Manga name exist';
            $err = -3;
        }
        return array('err' => $err, 'msg' => $msg);
    }

    function uploadCover() {
        $cfg['upload_path'] = COVER_DIR;
        $cfg['allowed_types'] = 'gif|jpg|png';
        $cfg['max_size'] = 1024 * 5;
        $cfg['encrypt_name'] = true;
        $cfg['max_width'] = '2048';
        $cfg['max_height'] = '1536';

        $this->upload->initialize($cfg);
        $err = array();
        if (!$this->upload->do_upload('file')) {
            $err['err'] = -1;
            $err['msg'] = 'Upload Failure';
            $err['data'] = $this->upload->display_errors();
        } else {
            $err['err'] = 0;
            $err['msg'] = 'Success.';
            $err['data'] = $this->upload->data();
            $this->resizeCover($err['data']['full_path']);
            chmod($err['data']['full_path'], 0777);
        }
        return $err;
    }

    private function resizeCover($full_path) {
        $rz['image_library'] = 'gd2';
        $rz['source_image'] = $full_path;
        $rz['width'] = COVER_WIDTH;
        $rz['height'] = COVER_HEIGHT;
        $this->load->library('image_lib', $rz);
        $this->image_lib->resize();
    }

    function getManga_by_id($id) {
        $manga = $this->db->get_where('manga', array('id' => $id))->row();
        $chapter = $this->mongo_db->order_by(array("chapter" => "asc"))->get('manga_' . $id);
        $manga->chapter = array();
        foreach ($chapter as $row)
            $manga->chapter[] = $row;

        function sortChapter($a, $b) {
            if ($a['chapter'] == $b['chapter']) {
                usort($manga->chapter, 'sortChapter');
                return 0;
            }
            return ($a['chapter'] < $b['chapter']) ? -1 : 1;
        }

        usort($manga->chapter, 'sortChapter');
        return $manga;
    }

    function getManga_slug_by_id($mangaId) {
        return $this->db->select('slug')->get_where('manga', array('id' => $mangaId))->row()->slug;
    }

    function parseLink_truyentranhtuan($url) {
        $html = getHtml_by_parse_link($url);
        $html .= '<script type="text/javascript">
					var tr = jQuery("#content-main table tr"),
						data = new Array();
					jQuery.each(tr, function(i, item) {
						var link = jQuery(item).find("a").attr("href");
						link && data.push(link);
					})
					top.manga.truyentranhtuanMessage(data);
					jQuery("html").remove();
				</script>';
        $path = TMP_DIR . '/manga_truyentranhtuan.html';
        return write_file($path, $html);
    }

    private function validateName($name) {
        return strlen($name) <= 100;
    }

    private function validateDescription($desc) {
        return mb_strlen($desc) <= 2000;
    }

    private function checkNameExist($name, $id = 0) {
        $query_u = $this->db->get_where('manga', array('name' => $name));
        if ($id != 0 && $query_u->num_rows > 0) {
            $result = $query_u->row();
            return $id != $result->id;
        } else
            return $query_u->num_rows > 0;
    }

    /**
     * Model to upload images to chapter folder
     * 
     * @parameter:
     * 		mangaId:
     * 		chapterId:
     * 		list imaga
     */
    function uploadChapterImage($slug, $chapterId) {
        $path = createImageLocation($slug, $chapterId);
        $cfg['upload_path'] = $path;
        $cfg['allowed_types'] = 'gif|jpg|png';
        $cfg['overwrite'] = true;
        $cfg['max_size'] = 1024 * 5;
        $cfg['encrypt_name'] = false;

        $this->upload->initialize($cfg);
        $err = array();
        if (!$this->upload->do_upload('file')) {
            $err['err'] = -1;
            $err['msg'] = 'Upload Failure';
            $err['data'] = $this->upload->display_errors();
        } else {
            $err['err'] = 0;
            $err['msg'] = 'Success.';
            $err['data'] = $this->upload->data();

            resizePic($err['data']['full_path'], $err['data']['image_width'], $err['data']['image_height']);
        }
        return $err;
    }

    /**
     * Make new chapter for a manga
     * 
     * @param type $mangaId: manga Id 
     * @param type $chapterId: chapter Id
     * @return type
     */
    function addNewChapter($mangaId, $chapterId) {
        $data = array(
            'chapter' => $chapterId,
            'images' => '',
            'update' => REQUEST_TIME,
            'created' => REQUEST_TIME
        );
        return $this->mongo_db->insert('manga_' . $mangaId, $data);
    }

    /**
     * Delete a chapter and all image files
     * @param type $slug
     * @param type $chapterId
     * @return type
     */
    function deleteChapter_by_id($slug, $chapterId, $mangaId) {
        $this->removeChapter_image_file($slug, $chapterId);
        return $this->mongo_db->where('chapter', $chapterId)->delete('manga_' . $mangaId);
    }

    /**
     * Get chapter detail of a manga
     * 
     * @param type $mangaId: manga Id
     * @param type $chapterId: chapter Id
     * @return type 
     */
    function getChapter_by_chapterId($mangaId, $chapterId) {
        $data = $this->mongo_db->where('chapter', $chapterId)->get('manga_' . $mangaId);
        return $data;
    }

    /**
     * Update image list to a chapter
     * 
     * @param type $arr
     * @return type 
     */
    function updateChapter_by_chapterId($arr) {
        $data = array('images' => $arr['images'], 'update' => REQUEST_TIME);
        $result = $this->mongo_db->where('chapter', $arr['chapterId'])->set($data)->update('manga_' . $arr['mangaId']);
        return $result;
    }

    /**
     * Validate chapter infor 
     * @param type $arr array data of manga 
     * @return type 
     */
    function getChapter_validate($arr) {
        extract($arr);

        $err = 0;
        $msg = array();
        //check manga id exit
        $mangaId = isset($mangaId) ? $mangaId : 0;
        if (!$this->checkMangaIdExist($mangaId)) {
            $msg['mangaId'] = 'Manga id not exist';
            $err = -1;
        }
        return array('err' => $err, 'msg' => $msg);
    }

    function getImage_by_multi_link($data, $slug, $chapterId, $mangaId) {
        $result = array();
        $s = array();
        foreach ($data as $url) {
            $i = array();
            if ($url) {
                $fileName = substr($url, strripos($url, '/') + 1);
                $path = createImageLocation($slug, $chapterId) . '/' . $fileName;

                $src = getImage_source($url);
                resizePic($src, $path);

                $relative = str_replace('./', "", $path);
                $i['furl'] = base_url() . $relative;
                $i['image_path'] = $relative;
                $s[] = $relative;
                $result[] = $i;
            }
        }
        sort($s);
        $this->updateChapter_by_chapterId(array('images' => serialize($s), 'chapterId' => $chapterId, 'mangaId' => $mangaId));
        return $result;
    }

    function getImage_by_single_link($url, $slug, $chapterId) {
        $fileName = substr($url, strripos($url, '/') + 1);
        $path = createImageLocation($slug, $chapterId) . '/' . $fileName;

        $src = getImage_source($url);
        resizePic($src, $path);

        $result = array();
        $relative = str_replace('./', "", $path);
        $result['furl'] = base_url() . $relative;
        $result['image_path'] = $relative;

        return $result;
    }

    function parseLinkContent_truyentranhtuan($url, $chapterId = 0, $cb = '') {
        $path = TMP_DIR . '/truyentranhtuan/';
        if (!file_exists($path))
            mkdir($path, 0755);

        $cb = $cb != '' ? $cb : 'chapter.truyentranhtuanMessage';
        $html = getHtml_by_parse_link($url);
        $html .= '<script type="text/javascript">
					top.' . $cb . '(JSON.stringify(slides2), "' . $chapterId . '");
					jQuery("html").remove();	
				</script>';
        $file = 'truyentranhtuan_' . REQUEST_TIME . '.html';
        $path .= $file;
        $wr = write_file($path, $html);

        return $wr ? base_url() . '/tmp/truyentranhtuan/' . $file : false;
    }

    function removeChapter_image_file($slug, $chapterId) {
        $path = MANGA_DIR . $slug . '/' . $chapterId;
        rrmdir($path);
    }

    /**
     * Check a manga is exist or not
     * 
     * @param type $id
     * @return type 
     */
    private function checkMangaIdExist($id = 0) {
        $query_u = $this->db->get_where('manga', array('id' => $id));
        return $query_u->num_rows > 0;
    }

}

?>
